package org.example.springmessage.controller;

import org.example.springmessage.domain.Message;
import org.example.springmessage.refult.R;
import org.example.springmessage.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.*;

@RestController
@RequestMapping("/message")
public class MessageController {
    @Autowired
    private MessageService messageService;

    @RequestMapping("/getAllMessages")
    public R getAllMessages() {
        List<Message> allMessages = messageService.getAllMessages();
        System.out.println(allMessages);
        return R.ok(allMessages);
    }

    @GetMapping("/getMessageById")
    public R getMessageById(@AuthenticationPrincipal UserDetails user) {
        String userid = user.getAuthorities().toString();
        userid = userid.substring(1,userid.length()-1);
        return R.ok(messageService.getByUserId(Integer.valueOf(userid)));
    }

    @PutMapping("/delete")
    public R delete(Integer id) {
        messageService.delete(id);
        return R.ok();
    }

    @PostMapping("/addMessage")
    public R addMessage(Message message, @AuthenticationPrincipal UserDetails user){
        String v = user.getAuthorities().toString();
        v = v.substring(1,v.length()-1);
        message.setUserid(Integer.valueOf(v));
        message.setDate(new Timestamp(System.currentTimeMillis()));
        return R.ok(messageService.addMessage(message));
    }

    @GetMapping("/getMessageByTag")
    public R getMessageByTag(String tag) {
        System.out.println(tag);
        return R.ok(messageService.getMessageByTag(tag));
    }

}
